//! # 性能监控模块测试
//! 
//! 本文件包含性能监控模块的集成测试和单元测试

use crate::performance_monitor::core::*;
use crate::performance_monitor::config::*;
use crate::performance_monitor::traits::*;
use crate::performance_monitor::alerts::*;
use rustcloud_core::{ServiceResult, ServiceError};
use std::time::Duration;

#[tokio::test]
async fn test_performance_monitor_creation() {
    let config = PerformanceMonitorConfig::default();
    let monitor = PerformanceMonitor::new(config);
    
    // 验证监控器创建成功
    assert!(!monitor.is_running().await);
}

#[tokio::test]
async fn test_performance_monitor_lifecycle() {
    let config = PerformanceMonitorConfig {
        collection_interval: Duration::from_millis(100),
        ..Default::default()
    };
    
    let monitor = PerformanceMonitor::new(config);
    
    // 启动监控器
    assert!(monitor.start().await.is_ok());
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(monitor.is_running().await);
    
    // 停止监控器
    assert!(monitor.stop().await.is_ok());
    assert!(!monitor.is_running().await);
}

#[tokio::test]
async fn test_performance_monitor_data_collection() {
    let config = PerformanceMonitorConfig {
        collection_interval: Duration::from_millis(100),
        ..Default::default()
    };
    
    let monitor = PerformanceMonitor::new(config);
    monitor.start().await.unwrap();
    
    // 等待数据收集
    tokio::time::sleep(Duration::from_millis(250)).await;
    
    // 验证数据收集
    let current_metrics = monitor.get_current_metrics().await;
    assert!(current_metrics.is_some());
    
    let history = monitor.get_metrics_history(None).await;
    assert!(!history.is_empty());
    
    let limited_history = monitor.get_metrics_history(Some(3)).await;
    assert!(limited_history.len() <= 3);
    
    monitor.stop().await.unwrap();
}

#[tokio::test]
async fn test_performance_monitor_alerts() {
    let thresholds = PerformanceThresholds {
        cpu_warning_threshold: 0.5,
        cpu_critical_threshold: 0.8,
        memory_warning_threshold: 0.6,
        memory_critical_threshold: 0.9,
        ..Default::default()
    };
    
    let config = PerformanceMonitorConfig {
        collection_interval: Duration::from_millis(100),
        thresholds,
        ..Default::default()
    };
    
    let monitor = PerformanceMonitor::new(config);
    monitor.start().await.unwrap();
    
    // 等待数据收集和警报生成
    tokio::time::sleep(Duration::from_millis(250)).await;
    
    // 验证警报历史
    let alerts = monitor.get_alert_history(None).await;
    // 注意：由于使用模拟数据，警报可能不会触发，这取决于模拟的阈值设置
    // 这里我们只验证函数能正常工作
    assert!(alerts.len() >= 0);
    
    let limited_alerts = monitor.get_alert_history(Some(2)).await;
    assert!(limited_alerts.len() <= 2);
    
    monitor.stop().await.unwrap();
}

#[tokio::test]
async fn test_performance_summary() {
    let config = PerformanceMonitorConfig {
        collection_interval: Duration::from_millis(100),
        ..Default::default()
    };
    
    let monitor = PerformanceMonitor::new(config);
    monitor.start().await.unwrap();
    
    // 等待数据收集
    tokio::time::sleep(Duration::from_millis(250)).await;
    
    // 验证性能摘要
    let summary = monitor.get_performance_summary().await;
    assert!(summary.uptime_seconds > 0);
    assert!(summary.data_points > 0);
    assert!(summary.avg_cpu_usage >= 0.0);
    assert!(summary.max_cpu_usage >= 0.0);
    assert!(summary.avg_memory_usage >= 0.0);
    assert!(summary.max_memory_usage >= 0.0);
    
    monitor.stop().await.unwrap();
}

#[tokio::test]
async fn test_concurrent_access() {
    let config = PerformanceMonitorConfig {
        collection_interval: Duration::from_millis(100),
        ..Default::default()
    };
    
    let monitor = PerformanceMonitor::new(config);
    monitor.start().await.unwrap();
    
    // 并发访问测试
    let monitor_clone1 = monitor.clone();
    let monitor_clone2 = monitor.clone();
    let monitor_clone3 = monitor.clone();
    
    let handles = vec![
        tokio::spawn(async move {
            for _ in 0..10 {
                let _metrics = monitor_clone1.get_current_metrics().await;
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        }),
        tokio::spawn(async move {
            for _ in 0..10 {
                let _history = monitor_clone2.get_metrics_history(Some(5)).await;
                tokio::time::sleep(Duration::from_millis(15)).await;
            }
        }),
        tokio::spawn(async move {
            for _ in 0..10 {
                let _alerts = monitor_clone3.get_alert_history(Some(5)).await;
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        }),
    ];
    
    // 等待所有任务完成
    for handle in handles {
        handle.await.unwrap();
    }
    
    monitor.stop().await.unwrap();
}

#[tokio::test]
async fn test_multiple_starts_and_stops() {
    let config = PerformanceMonitorConfig {
        collection_interval: Duration::from_millis(50),
        ..Default::default()
    };
    
    let monitor = PerformanceMonitor::new(config);
    
    // 多次启动应该失败
    assert!(monitor.start().await.is_ok());
    assert!(monitor.start().await.is_err()); // 第二次启动应该失败
    
    // 停止
    assert!(monitor.stop().await.is_ok());
    
    // 停止后再停止应该成功（幂等性）
    assert!(monitor.stop().await.is_ok());
    
    // 停止后可以重新启动
    assert!(monitor.start().await.is_ok());
    assert!(monitor.stop().await.is_ok());
}